<?php


namespace App\Admin\Actions\Tools;


use App\Admin\Actions\BatchAction;
use App\Expert;
use App\Models\AdminUser;
use App\PatentApply;
use App\PatentAssess;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class AssignExpertBatchAction extends BatchAction
{
    protected $selector = '.assign-expert-posts';

    public function handle(Collection $collection, Request $request)
    {
        $expert = $request->get('expert_id') ?: [];
        $expert = collect($expert)->filter()->toArray();
        foreach ($collection as $model) {
            if ($model instanceof PatentApply) {
                $model->assesses()->whereNotIn('expert_id', $expert)->delete();
                foreach ($expert as $expert_id) {
                    $res = PatentAssess::withTrashed()->where([['patent_apply_id', $model['id']], ['expert_id', $expert_id]])->first();
                    if (!$res) {
                        $model->assesses()->create(['expert_id' => $expert_id]);
                    } elseif ($res->deleted_at) {
                        $res->restore();
                    }
                }
                $model->syncScore();
            }
        }
        return $this->response()->success('操作成功！')->refresh();
    }


    public function form()
    {
        $this->multipleSelect('expert_id', '请选择专家')->options(Expert::expertSelectOptions())->required();
    }

    public function html()
    {
        return "<a class='assign-expert-posts btn btn-sm btn-primary'>指派专家</a>";
    }

    public function authorize(AdminUser $user, Collection $collection)
    {
        return $user->role_type == 1;
    }

}
